package model

import (
	"database/sql"
	"encoding/json"
	"iot-base/auth/utils"
	"strings"
	"time"
)

const TimeFormat = "2006-01-02 15:04:05"

type Model struct {
	ID        int64     `gorm:"primary key" json:"id"`
	CreatedAt time.Time `json:"-"`
	UpdatedAt time.Time `json:"-"`
}

func (m Model) AutoId() {
	m.ID = utils.GetUid()
}

func (m Model) AutoCreatedAt() {
	m.CreatedAt = time.Now()
}

func (m Model) AutoUpdatedAt() {
	m.UpdatedAt = time.Now()
}

type JsonNullTime struct {
	sql.NullTime
}

func (v JsonNullTime) MarshalJSON() ([]byte, error) {
	if v.Valid {
		return json.Marshal(v.Time.Format("2006-01-02 15:04:05"))
	} else {
		return json.Marshal("")
	}
}

type Datetime time.Time

func (t Datetime) MarshalJSON() ([]byte, error) {
	return json.Marshal(time.Time(t).Format(TimeFormat))
}

func (t *Datetime) UnmarshalJSON(data []byte) error {
	// 指定解析的格式
	now, err := time.ParseInLocation("2006-01-02 15:04:05", strings.ReplaceAll(string(data), "\"", ""), time.Local)
	if err != nil {
		*t = Datetime{}
	} else {
		*t = Datetime(now)
	}
	return err
}
